<template>
  <el-card>
    <h3 class="center">修改角色 {{ roleName }} 的权限</h3>
    <el-tree
      ref="tree"
      :data="roleAuthList"
      show-checkbox
      :props="treeProps"
      :default-checked-keys="checkedIds"
      node-key="id"
    >
    </el-tree>
    <div class="top10">
      <el-button type="primary" @click="updateRoleAuth">保存</el-button>
      <el-button type="" @click="gotoRoleList">取消</el-button>
    </div>
  </el-card>
</template>

<script>
export default {
  props: {},
  computed: {
    roleId() {
      return this.$route.params.roleId || ''
    },
    roleName() {
      return this.$route.query.roleName || ''
    },
    redirect() {
      return this.$route.query.redirect || ''
    }
  },
  data() {
    return {
      checkedIds: [],
      roleAuthList: [],
      treeProps: {
        label: 'name',
        children: 'children'
      }
    }
  },
  methods: {
    // 返回角色列表
    gotoRoleList() {
      const { redirect } = this
      if (redirect) {
        this.$router.push({ path: redirect })
      } else {
        this.$router.push({ name: 'Role' })
      }
    },
    // 保存修改
    async updateRoleAuth() {
      let checkedIds = this.$refs.tree.getCheckedKeys()
      const res = await this.$API.role.updateRoleAuth(this.roleId, checkedIds)
      if (res.ok) {
        this.$message({ type: 'success', message: '修改成功' })
        // 回到角色列表
        this.gotoRoleList()
      } else {
        this.$message({
          type: 'error',
          message: res.message + ':' + (res.data || '')
        })
      }
    },
    // 获取已经选中节点的ID
    getCheckedIds(list) {
      for (let i in list) {
        let item = list[i]
        if (item.select) {
          this.checkedIds.push(item.id)
        }
        if (item.children && item.children.length != 0) {
          this.getCheckedIds(item.children)
        }
      }
    },
    async getRoleAuthList() {
      const res = await this.$API.role.getRoleJurisdiction(this.roleId)
      if (res.ok) {
        this.roleAuthList = res.data.children[0].children
        this.getCheckedIds(this.roleAuthList)
      } else {
        this.$message({
          type: 'error',
          message: res.message + ':' + (res.data || '')
        })
      }
    }
  },
  created() {
    this.getRoleAuthList()
  }
}
</script>

<style>
.center {
  text-align: center;
}

.top10 {
  margin-top: 10px;
}
</style>
